<template>
  <n-grid x-gap="12" :cols="16" class="drag-region">

    <!-- logo -->
    <n-gi :span="2" class="logo-and-search">
      <a href="javascript:;">
        <n-icon size="50" @click="enterMainView">
          <svg class="icon" aria-hidden="true">
            <use xlink:href="#icon-listen"></use>
          </svg>
        </n-icon>
      </a>
    </n-gi>

    <!-- 搜索框 -->
    <n-gi :span="4" class="logo-and-search">
      <n-input v-model:value="searchValue" @keydown.enter="searchDebounce" clearable placeholder="输入想要搜索的歌曲、歌词或歌手" />
    </n-gi>

    <n-gi :span="4" class="title">
      <n-gradient-text :gradient="{ deg: 180, from: 'rgb(85, 85, 85)', to: 'rgb(170, 170, 170)' }">
        {{ usePlayConfig.audioName.split('.')[0] }}
      </n-gradient-text>
    </n-gi>

    <!-- options组 -->
    <n-gi :span="6" class="browserWindow-options">
      <n-tooltip placement="bottom" trigger="hover">
        <template #trigger>
          <n-icon class="options-icon" :size="iconSize" :component="UserOutlined" @click="enterUserView" />
        </template>
        <span>{{ userInfo.username == '' ? '未登录' : userInfo.username }}</span>
      </n-tooltip>
      <n-tooltip placement="bottom" trigger="hover">
        <template #trigger>
          <n-icon v-if="useSystemConfig.theme == 'null'" class="options-icon" :size="iconSize" :component="WeatherSunnyHigh20Regular" @click="changeTheme" />
          <n-icon v-if="useSystemConfig.theme == 'dark'" class="options-icon" :size="iconSize" :component="MoonStars" @click="changeTheme" />
        </template>
        <span>切换主题</span>
      </n-tooltip>
      <n-tooltip placement="bottom" trigger="hover">
        <template #trigger>
          <n-icon class="options-icon" :size="iconSize" :component="SettingOutlined" @click="enterSetting" />
        </template>
        <span>设置</span>
      </n-tooltip>

      <n-tooltip placement="bottom" trigger="hover">
        <template #trigger>
          <n-icon class="options-icon" :size="iconSize" :component="ViewportNarrow" @click="miniBrowserWindow" />
        </template>
        <span>mini</span>
      </n-tooltip>
      <n-tooltip placement="bottom" trigger="hover">
        <template #trigger>
          <n-icon class="options-icon" :size="iconSize" :component="SubtractCircle12Regular" @click="narrowBrowserWindow" />
        </template>
        <span>缩小</span>
      </n-tooltip>
      <n-tooltip placement="bottom" trigger="hover">
        <template #trigger>
          <n-icon class="options-icon" :size="iconSize" :component="ArrowMinimize16Filled" @click="hiddenBrowserWindow" />
        </template>
        <span>隐藏</span>
      </n-tooltip>
      <n-tooltip placement="bottom" trigger="hover">
        <template #trigger>
          <n-icon class="options-icon" :size="iconSize" :component="CloseCircleOutlined" @click="closeBrowserWindow" />
        </template>
        <span>关闭</span>
      </n-tooltip>
    </n-gi>

  </n-grid>
</template>

<script setup lang="ts">
import { ViewportNarrow, MoonStars } from '@vicons/tabler'
import { CloseCircleOutlined, UserOutlined, SettingOutlined } from '@vicons/antd'
import { SubtractCircle12Regular, ArrowMinimize16Filled, WeatherSunnyHigh20Regular } from '@vicons/fluent'
import { ref } from 'vue'
import { useRouter } from 'vue-router'
import { useMessage } from 'naive-ui'
import { onMounted, getCurrentInstance } from 'vue'
import { useSystemConfigStore, usePlayConfigStore, usePlayListStore, userInfoStore } from '../../store'
import { updateUserLevel, searchAudio } from '../../ajax/index'
import { importPlayListMode, matchMyLike } from '../../util/calculate'
import _ from 'lodash'

window.$message = useMessage()

onMounted(async () => {
  // 改变播放模式
  window.electron.ipcRenderer.send('changePlayMode', usePlayConfig.playMode)

})

const instance = getCurrentInstance()
const message = useMessage()
const useSystemConfig = useSystemConfigStore()
const usePlayConfig = usePlayConfigStore()
const usePlayList = usePlayListStore()
const userInfo = userInfoStore()
const router = useRouter()
const searchValue = ref('')
// icon图标的大小
const iconSize = ref(30)

let timeId: any = null
let countId: any = null

// 定时器关闭监听
instance?.proxy?.$Bus.on("countDown", function (params: any) {
  timeId = setTimeout(() => {
    clearInterval(countId)
    useSystemConfig.changeCountDown(0)
    window.electron.ipcRenderer.send('closeBrowserWindow')
  }, params.time);

  countId = setInterval(() => {
    let t = Number((useSystemConfig.countDown - 1000).toFixed(0))
    useSystemConfig.changeCountDown(t)
  }, 1000);
})
// 定时器关闭取消监听
instance?.proxy?.$Bus.on("countDownCancel", function () {
  clearTimeout(timeId)
  clearInterval(countId)
})
// 乐库搜索列表点击tag触发搜索事件
instance?.proxy?.$Bus.on('searchKeyWord', async function (params: any) {

  // 搜索前清空乐库列表
  usePlayList.resetAudioLibraryList()

  // 搜索并写入值
  const result = await searchAudio(params == undefined ? searchValue.value : params.keyword, usePlayList.audioLibraryPage, 10)
  if (result.data.code == 0) {
    usePlayList.audioLibrarySearchCount = result.data.count
    await importPlayListMode('audioLibrary', result.data.data)
  } else {
    message.warning(result.data.message)
  }

  // 匹配我的喜欢标识
  await matchMyLike('audioLibrary')

})

// 搜索歌曲、歌词时间
const searchAudioEvent = async () => {

  if (searchValue.value) { // 有值才搜索

    // 搜索值有变动则清空乐库列表
    usePlayList.resetAudioLibraryList()
    usePlayList.audioLibraryPage = 1

    // 系统配置更改
    useSystemConfig.changeShowAudioLibraryHall(false)
    useSystemConfig.changePage('audioLibrary')
    router.push({ name: 'audioLibrary' })

    // 搜索并写入值
    const result = await searchAudio(searchValue.value, usePlayList.audioLibraryPage, 10)
    if (result.data.code == 0) {
      usePlayList.audioLibrarySearchCount = result.data.count
      await importPlayListMode('audioLibrary', result.data.data)
    }

    // 匹配我的喜欢标识
    await matchMyLike('audioLibrary')

  }

}
const searchDebounce = _.debounce(searchAudioEvent, 500)


// 进入主界面
const enterMainView = () => {
  router.push({ name: `${useSystemConfig.page}` })
}
// 进入用户界面 
const enterUserView = () => {
  userInfo.loginState == true ? router.push({ name: 'userInfo' }) : router.push({ name: 'registerOrLogin' })
}
// 切换主题
const changeTheme = () => {
  instance?.proxy?.$Bus.emit("changeTheme", { theme: useSystemConfig.theme == "null" ? "dark" : "null" })
}
// 进入设置界面
const enterSetting = () => {
  router.push({ name: useSystemConfig.setPage })
}
// mini窗口
const miniBrowserWindow = () => {
  useSystemConfig.changeLoading(true, '开启mini模式中')
  setTimeout(() => {
    useSystemConfig.changeLoading(false, '加载中')
  }, 3000);
  message.warning('开发中，敬请期待...')
}
// 最小化窗口
const narrowBrowserWindow = () => {
  window.electron.ipcRenderer.send('narrowBrowserWindow')
}
// 隐藏窗口
const hiddenBrowserWindow = () => {
  window.electron.ipcRenderer.send('hiddenBrowserWindow')
}
// 关闭窗口--上传用户听了多长时间
const closeBrowserWindow = async () => {
  if (userInfo.loginState) {
    await updateUserLevel(usePlayConfig.playTime)
    usePlayConfig.changePlayTime(0)
  }
  window.electron.ipcRenderer.send('closeBrowserWindow')
}
// 关闭窗口--上传用户听了多长时间
window.api.updateUserLevel(async () => {
  if (userInfo.loginState) {
    await updateUserLevel(usePlayConfig.playTime)
    usePlayConfig.changePlayTime(0)
  }
})

</script>
<style scoped lang="less">
.drag-region {
  -webkit-app-region: drag;
  width: 100%;
  height: 100%;
  display: flex;
  align-items: center;
  justify-content: space-between;


  .logo-and-search {
    display: flex;
    align-items: center;
    justify-content: center;
    -webkit-app-region: no-drag;
  }

  .title {
    display: flex;
    justify-content: space-around;
    align-items: center;
  }

  .browserWindow-options {
    -webkit-app-region: no-drag;
    display: flex;
    justify-content: space-around;

    .options-icon {
      margin-right: 10px;
    }

    .options-icon:nth-child(2) {
      margin-right: 30px;
    }
  }
}
</style>
